// import * as cheerio from 'cheerio';
import { tsImportType } from '@babel/types';
import { getHtmlDomWithRetry } from '../../lib/http';
import { Book } from '../../main/Book';
import { getAttachment } from '../../lib/attachments';
import { Chapter } from '../../main/Chapter';
import { BaseRuleClass, ChapterParseObject } from '../../rules';

const externalTexts = [
    '小主，这个章节后面还有哦，请点击下一页继续阅读，后面更精彩！',
    '本小章还未完，请点击下一页继续阅读后面精彩内容！',
    '这章没有结束，请点击下一页继续阅读！',
];

export default class ShuHaiGe extends BaseRuleClass {
    constructor() {
        super();
    }

    public async bookParse(): Promise<Book> {
        // 书籍信息
        const bookEl = document.querySelector('#info')!;
        const bookName = bookEl.querySelector('h1')!.textContent!;
        // 作者
        const author = bookEl.querySelector('a')!.textContent!;
        // 更新时间
        const updateTime = bookEl.querySelector('p:nth-child(4)')?.textContent!.replace('最后更新：', '').trim()!;
        // 介绍
        const introEl = document.querySelector('#intro')!.childNodes[0];
        const introText = introEl.textContent!;
        // 封面
        const coverEl = document.querySelector('#fmimg > img') as HTMLImageElement;
        const coverUrl = coverEl.getAttribute('src')!;
        const cover = await getAttachment(coverUrl, 'TM', '', true);
        // 章节
        const chapters: Chapter[] = [];
        const listEl = document.querySelector('#list > dl')!;
        const nodes = listEl.childNodes;
        let chapterNum = 0;
        for (let i = 0, len = nodes.length, chaptersStarted = -1; i < len; i++) {
            const node = nodes[i] as HTMLElement;
            // 第一个dt为最新章节，第二个dt才开始全部章节列表
            if (chaptersStarted < 1) {
                if (node.tagName.toLowerCase() === 'dt') {
                    chaptersStarted += 1;
                }
                continue;
            }
            chapterNum += 1;
            const chapterInfoEl = node.childNodes[0]! as HTMLAnchorElement;
            const chapterPath = chapterInfoEl.getAttribute('href');
            const chapterName = chapterInfoEl.textContent;
            const chapter = new Chapter({
                bookUrl: location.href,
                bookname: bookName,
                chapterUrl: location.origin + chapterPath,
                chapterNumber: chapterNum,
                chapterName,
                isVIP: false,
                isPaid: false,
                sectionName: '',
                sectionNumber: 1,
                sectionChapterNumber: 1,
                chapterParse: this.chapterParse.bind(this),
                charset: 'utf-8',
                options: {},
            });
            chapters.push(chapter);
            // if (chapterNum >= 10) break; // 只抓取前10章（测试用
        }
        return new Book({
            bookUrl: location.href,
            bookname: bookName,
            author,
            introduction: introText,
            introductionHTML: null,
            additionalMetadate: {
                cover,
                lastModified: new Date(updateTime).getTime(),
            },
            chapters,
        });
    }

    public async chapterParse(
        chapterUrl: string,
        chapterName: string | null,
        isVIP: boolean,
        isPaid: boolean | null,
        charset: string,
        options: Record<string, any>
    ): Promise<ChapterParseObject> {
        const docList = [];
        let hasNextPage = true;
        do {
            const doc = await getHtmlDomWithRetry(chapterUrl, charset);
            docList.push(doc);

            const nextPageEl = doc?.querySelector('#A3');
            hasNextPage = nextPageEl?.textContent === '下一页';
            if (hasNextPage) {
                chapterUrl = location.origin + nextPageEl!.getAttribute('href');
            }
        } while (hasNextPage);
        const contentEl: HTMLElement = document.createElement('div');
        let contentText = '';
        for (let i = 0; i < docList.length; i++) {
            const doc = docList[i];
            const docContentEl: HTMLElement = doc?.querySelector('#content')!;
            const pList = docContentEl.childNodes;
            for (let i = 0; i < pList.length; i++) {
                const node = pList[i] as HTMLElement;
                if (node.tagName.toLowerCase() === 'br') {
                    contentEl.appendChild(document.createElement('br'));
                    contentText += '\n';
                } else {
                    const text = node.textContent!.trim();
                    const dynamicExternalText = `喜欢${this.book?.bookname}请大家收藏：(www.shuhaige.net)重生之将门毒后书海阁小说网更新速度全网最快。`
                    if (externalTexts.indexOf(text) === -1 && text !== dynamicExternalText) {
                        const temp = document.createElement('p');
                        temp.innerHTML = text;
                        contentEl.appendChild(temp);
                        contentText += `\t${text}\n`;
                    }
                }
            }
        }
        return {
            chapterName,
            contentRaw: contentEl,
            contentHTML: contentEl,
            contentText: contentText,
            contentImages: null,
            additionalMetadate: null,
        };
    };
}
